package com.woniu.springbootvideo.controller;

import com.woniu.springbootvideo.pojo.Video;
import com.woniu.springbootvideo.service.IVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("video")
@CrossOrigin
public class VideoController {
    @Autowired
    private IVideoService videoService;

    @RequestMapping("findTen")
    @ResponseBody
    public List<Video> findTenByType(Integer id){
        List<Video> videoList = videoService.findTenByType(id);
        System.out.println("findTenByType"+"=============="+id);
        return videoList;
    }
    @RequestMapping("save")
    @ResponseBody
    public String save(@RequestParam("file") MultipartFile file, HttpServletRequest req, Video video, BindingResult bindingResult) {
        String realPath = req.getServletContext().getRealPath("/upload");
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        try {
            file.transferTo(new File(folder, newName));
            String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/upload/" + newName;
            System.out.println(url);
            System.out.println(video+"===========");
            video.setVideoUrl(url);
            videoService.save(video);
            return "success";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "fail";
    }
    @RequestMapping("findQuery")
    @ResponseBody
    public List<Video> findAllByType(String videoProfess,
                                     String videoLoc,
                                     Integer videoClass,
                                     String videoUser,
                                     Integer videoType){
        Video video = new Video();
        video.setVideoProfess(videoProfess);
        video.setVideoLoc(videoLoc);
        video.setVideoClass(videoClass);
        video.setVideoUser(videoUser);
        video.setVideoType(videoType);
        List<Video> videoList = videoService.findAllByType(video);
        System.out.println("findAll"+"=============="+video);
        return videoList;
    }
}
